package MemberService

import (
	"errors"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"time"
)

// CoinChange 会员币变更，包含余额和积分
// plusOrreduce 符号 + -
// typeStr 类型 integral_coin 和 money_coin
// srcType 类型
// memberId 所属会员
// srcId 源ID
// coin 币
// remark 备注
// opAdminId 操作的管理员ID
// opMemberId 操作的会员ID
func CoinChange(tx *gdb.TX, plusOrreduce, typeStr, srcType string, memberId, srcId, coin int, remark string,
	opAdminId, opMemberId int) error {

	allowType := []string{
		"integral_coin",
		"money_coin",
	}
	if !gstr.InArray(allowType, typeStr) {
		return errors.New("不支持" + typeStr + " 可用值:" + strings.Join(allowType, ","))
	}
	allowFuhao := []string{
		"+",
		"-",
	}
	if !gstr.InArray(allowFuhao, plusOrreduce) {
		return errors.New("不支持" + plusOrreduce + " 可用值:" + strings.Join(allowFuhao, ","))
	}
	// 如果是会员余额付款的话，扣款
	_, err := tx.Model("member").Where("id",
		memberId).Update(g.Map{
		typeStr: gdb.Raw(typeStr + plusOrreduce + gconv.String(coin)),
	})
	if err != nil {
		return err
	}
	// 写会员日志
	_, err = tx.Model("member_finance").Insert(g.Map{
		"member_id":    memberId,
		"type_name":    typeStr,
		"coin":         plusOrreduce + gconv.String(coin),
		"src_type":     srcType,
		"src_id":       srcId,
		"op_member_id": opMemberId,
		"op_admin_id":  opAdminId,
		"create_time":  time.Now().Unix(),
		"remark":       remark,
	})
	if err != nil {
		return err
	}

	return nil
}
